# -*- coding: utf-8 -*-
"""
日期计算标签页
提供各种日期计算功能的用户界面
"""

from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QGridLayout,
                            QLabel, QPushButton, QDateEdit, QSpinBox, QComboBox,
                            QTextEdit, QFrame, QGroupBox, QButtonGroup, QRadioButton,
                            QApplication, QMessageBox, QScrollArea)
from PyQt5.QtCore import Qt, QDate, pyqtSignal
from PyQt5.QtGui import QFont, QTextCursor

import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from core.date_calculator import DateCalculator


class DateCalculatorTab(QWidget):
    """日期计算标签页"""
    
    # 信号定义
    calculation_completed = pyqtSignal(dict)
    
    def __init__(self, history_manager=None):
        super().__init__()
        self.calculator = DateCalculator()
        self.history_manager = history_manager
        self.init_ui()
        self.connect_signals()
    
    def init_ui(self):
        """初始化用户界面"""
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(20, 20, 20, 20)
        main_layout.setSpacing(20)
        
        # 创建水平分割布局
        content_layout = QHBoxLayout()
        content_layout.setSpacing(25)
        
        # 左侧：输入和控制区域
        left_widget = QWidget()
        left_layout = QVBoxLayout(left_widget)
        left_layout.setContentsMargins(0, 0, 0, 0)
        left_layout.setSpacing(20)
        
        # 创建输入区域
        input_group = self.create_input_group()
        left_layout.addWidget(input_group)
        
        # 创建操作按钮区域
        button_group = self.create_button_group()
        left_layout.addWidget(button_group)
        
        left_layout.addStretch()
        
        # 右侧：结果显示区域
        result_group = self.create_result_group()
        
        # 设置左右比例 (左侧40%，右侧60%)
        content_layout.addWidget(left_widget, 2)  # 左侧占2份
        content_layout.addWidget(result_group, 3)  # 右侧占3份
        
        main_layout.addLayout(content_layout)
    
    def create_input_group(self):
        """创建输入区域"""
        group_box = QGroupBox("日期计算设置")
        group_box.setFont(QFont("Microsoft YaHei", 11, QFont.Bold))
        group_box.setMinimumHeight(220)
        group_box.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                border: 2px solid #dee2e6;
                border-radius: 8px;
                margin-top: 10px;
                padding-top: 15px;
                background-color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 15px;
                padding: 0 8px 0 8px;
                color: #495057;
                background-color: #ffffff;
            }
        """)
        layout = QGridLayout(group_box)
        layout.setSpacing(18)
        layout.setContentsMargins(25, 30, 25, 25)
        
        # 基础日期选择
        base_date_label = QLabel("基础日期:")
        base_date_label.setMinimumWidth(80)
        layout.addWidget(base_date_label, 0, 0)
        
        self.base_date_edit = QDateEdit()
        self.base_date_edit.setDate(QDate.currentDate())
        self.base_date_edit.setCalendarPopup(True)
        self.base_date_edit.setDisplayFormat("yyyy年MM月dd日")
        self.base_date_edit.setMinimumWidth(150)
        self.base_date_edit.setMinimumHeight(30)
        layout.addWidget(self.base_date_edit, 0, 1)
        
        # 快速日期按钮
        quick_date_layout = QHBoxLayout()
        quick_date_layout.setSpacing(8)
        
        today_btn = QPushButton("今天")
        today_btn.setMinimumHeight(30)
        today_btn.clicked.connect(lambda: self.base_date_edit.setDate(QDate.currentDate()))
        quick_date_layout.addWidget(today_btn)
        
        tomorrow_btn = QPushButton("明天")
        tomorrow_btn.setMinimumHeight(30)
        tomorrow_btn.clicked.connect(lambda: self.base_date_edit.setDate(QDate.currentDate().addDays(1)))
        quick_date_layout.addWidget(tomorrow_btn)
        
        yesterday_btn = QPushButton("昨天")
        yesterday_btn.setMinimumHeight(30)
        yesterday_btn.clicked.connect(lambda: self.base_date_edit.setDate(QDate.currentDate().addDays(-1)))
        quick_date_layout.addWidget(yesterday_btn)
        
        quick_date_layout.addStretch()
        layout.addLayout(quick_date_layout, 0, 2, 1, 3)
        
        # 计算类型选择
        calc_type_label = QLabel("计算类型:")
        calc_type_label.setMinimumWidth(80)
        layout.addWidget(calc_type_label, 1, 0)
        
        self.calc_type_group = QButtonGroup()
        
        calc_type_layout = QHBoxLayout()
        calc_type_layout.setSpacing(20)
        
        self.add_radio = QRadioButton("加上")
        self.add_radio.setChecked(True)
        self.add_radio.setMinimumHeight(25)
        calc_type_layout.addWidget(self.add_radio)
        
        self.subtract_radio = QRadioButton("减去")
        self.subtract_radio.setMinimumHeight(25)
        calc_type_layout.addWidget(self.subtract_radio)
        
        # 手动设置按钮组
        self.calc_type_group.addButton(self.add_radio, 1)
        self.calc_type_group.addButton(self.subtract_radio, -1)
        
        calc_type_layout.addStretch()
        layout.addLayout(calc_type_layout, 1, 1, 1, 2)
        
        # 时间单位和数值
        unit_label = QLabel("时间单位:")
        unit_label.setMinimumWidth(80)
        layout.addWidget(unit_label, 2, 0)
        
        self.unit_combo = QComboBox()
        self.unit_combo.addItems(["天", "周", "月", "年", "工作日"])
        self.unit_combo.setMinimumHeight(30)
        self.unit_combo.setMinimumWidth(100)
        layout.addWidget(self.unit_combo, 2, 1)
        
        amount_label = QLabel("数量:")
        amount_label.setMinimumWidth(50)
        layout.addWidget(amount_label, 2, 2)
        
        self.amount_spin = QSpinBox()
        self.amount_spin.setRange(0, 10000)
        self.amount_spin.setValue(1)
        self.amount_spin.setMinimumHeight(30)
        self.amount_spin.setMinimumWidth(80)
        layout.addWidget(self.amount_spin, 2, 3)
        
        # 间隔计算区域
        interval_label = QLabel("或计算间隔:")
        interval_label.setMinimumWidth(80)
        layout.addWidget(interval_label, 3, 0)
        
        end_date_label = QLabel("结束日期:")
        end_date_label.setMinimumWidth(80)
        layout.addWidget(end_date_label, 3, 1)
        
        self.end_date_edit = QDateEdit()
        self.end_date_edit.setDate(QDate.currentDate().addDays(7))
        self.end_date_edit.setCalendarPopup(True)
        self.end_date_edit.setDisplayFormat("yyyy年MM月dd日")
        self.end_date_edit.setMinimumWidth(150)
        self.end_date_edit.setMinimumHeight(30)
        layout.addWidget(self.end_date_edit, 3, 2, 1, 2)
        
        return group_box
    
    def create_button_group(self):
        """创建按钮区域"""
        frame = QFrame()
        frame.setMinimumHeight(60)
        layout = QHBoxLayout(frame)
        layout.setSpacing(15)
        layout.setContentsMargins(20, 10, 20, 10)
        
        # 计算按钮
        self.calculate_btn = QPushButton("🧮 开始计算")
        self.calculate_btn.setMinimumHeight(45)
        self.calculate_btn.setMinimumWidth(120)
        self.calculate_btn.setStyleSheet("""
            QPushButton {
                background-color: #007bff;
                color: white;
                border: none;
                border-radius: 8px;
                font-size: 13px;
                font-weight: bold;
                padding: 8px 16px;
            }
            QPushButton:hover {
                background-color: #0056b3;
            }
            QPushButton:pressed {
                background-color: #004085;
            }
        """)
        layout.addWidget(self.calculate_btn)
        
        # 间隔计算按钮
        self.interval_btn = QPushButton("📏 计算间隔")
        self.interval_btn.setMinimumHeight(45)
        self.interval_btn.setMinimumWidth(120)
        self.interval_btn.setStyleSheet("""
            QPushButton {
                background-color: #28a745;
                color: white;
                border: none;
                border-radius: 8px;
                font-size: 13px;
                font-weight: bold;
                padding: 8px 16px;
            }
            QPushButton:hover {
                background-color: #1e7e34;
            }
            QPushButton:pressed {
                background-color: #155724;
            }
        """)
        layout.addWidget(self.interval_btn)
        
        # 添加间隔
        layout.addStretch()
        
        # 清空按钮
        clear_btn = QPushButton("🗑️ 清空")
        clear_btn.setMinimumHeight(45)
        clear_btn.setMinimumWidth(100)
        clear_btn.setStyleSheet("""
            QPushButton {
                background-color: #6c757d;
                color: white;
                border: none;
                border-radius: 8px;
                font-size: 12px;
                padding: 8px 16px;
            }
            QPushButton:hover {
                background-color: #545b62;
            }
        """)
        clear_btn.clicked.connect(self.clear_inputs)
        layout.addWidget(clear_btn)
        
        # 复制结果按钮
        copy_btn = QPushButton("📋 复制结果")
        copy_btn.setMinimumHeight(45)
        copy_btn.setMinimumWidth(120)
        copy_btn.setStyleSheet("""
            QPushButton {
                background-color: #17a2b8;
                color: white;
                border: none;
                border-radius: 8px;
                font-size: 12px;
                padding: 8px 16px;
            }
            QPushButton:hover {
                background-color: #117a8b;
            }
        """)
        copy_btn.clicked.connect(self.copy_result)
        layout.addWidget(copy_btn)
        
        return frame
    
    def create_result_group(self):
        """创建结果显示区域"""
        group_box = QGroupBox("计算结果")
        group_box.setFont(QFont("Microsoft YaHei", 11, QFont.Bold))
        group_box.setMinimumHeight(500)
        group_box.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                border: 2px solid #dee2e6;
                border-radius: 8px;
                margin-top: 10px;
                padding-top: 15px;
                background-color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 15px;
                padding: 0 8px 0 8px;
                color: #495057;
                background-color: #ffffff;
            }
        """)
        layout = QVBoxLayout(group_box)
        layout.setContentsMargins(25, 30, 25, 25)
        layout.setSpacing(15)
        
        self.result_text = QTextEdit()
        self.result_text.setReadOnly(True)
        self.result_text.setFont(QFont("Microsoft YaHei", 11))
        self.result_text.setMinimumHeight(420)
        self.result_text.setStyleSheet("""
            QTextEdit {
                background-color: #f8f9fa;
                border: 2px solid #e9ecef;
                border-radius: 8px;
                padding: 15px;
                line-height: 1.6;
                color: #495057;
            }
            QTextEdit:focus {
                border-color: #007bff;
                background-color: #ffffff;
            }
        """)
        self.result_text.setPlaceholderText("计算结果将在这里显示...\n\n提示：\n• 选择基础日期\n• 选择计算类型和数量\n• 点击开始计算按钮")
        layout.addWidget(self.result_text)
        
        return group_box
    
    def connect_signals(self):
        """连接信号和槽"""
        self.calculate_btn.clicked.connect(self.perform_calculation)
        self.interval_btn.clicked.connect(self.calculate_interval)
        self.calculation_completed.connect(self.display_result)
    
    def perform_calculation(self):
        """执行日期计算"""
        try:
            base_date = self.base_date_edit.date().toPyDate()
            amount = self.amount_spin.value()
            unit = self.unit_combo.currentText()
            
            # 更可靠的方法：直接检查哪个按钮被选中
            if self.subtract_radio.isChecked():
                direction = -1
            else:
                direction = 1
            
            # 根据方向调整数量
            amount = amount * direction
            
            # 根据单位执行不同的计算
            if unit == "天":
                result = self.calculator.add_days(base_date, amount)
            elif unit == "周":
                result = self.calculator.add_days(base_date, amount * 7)
            elif unit == "月":
                result = self.calculator.add_months(base_date, amount)
            elif unit == "年":
                result = self.calculator.add_months(base_date, amount * 12)
            elif unit == "工作日":
                result = self.calculator.add_business_days(base_date, amount)
            else:
                raise ValueError(f"不支持的时间单位: {unit}")
            
            self.calculation_completed.emit(result)
            
            # 添加到历史记录
            if self.history_manager:
                input_data = {
                    'base_date': str(base_date),
                    'amount': abs(amount),
                    'unit': unit,
                    'operation': "减去" if amount < 0 else "加上"
                }
                self.history_manager.add_calculation_record("日期计算", input_data, result)
            
        except Exception as e:
            error_msg = str(e)
            if "2025" in error_msg or "year" in error_msg.lower():
                QMessageBox.warning(self, "年份提示", 
                    "注意：节假日数据目前只支持2004-2023年。\n"
                    "对于其他年份，将按照普通工作日计算（周一至周五为工作日）。\n"
                    "日期计算功能正常可用。")
                # 重新尝试计算，忽略节假日错误
                try:
                    base_date = self.base_date_edit.date().toPyDate()
                    amount = self.amount_spin.value()
                    unit = self.unit_combo.currentText()
                    
                    # 更可靠的方法：直接检查哪个按钮被选中
                    if self.subtract_radio.isChecked():
                        direction = -1
                    else:
                        direction = 1
                    
                    amount = amount * direction
                    
                    if unit == "天":
                        result = self.calculator.add_days(base_date, amount)
                    elif unit == "周":
                        result = self.calculator.add_days(base_date, amount * 7)
                    elif unit == "月":
                        result = self.calculator.add_months(base_date, amount)
                    elif unit == "年":
                        result = self.calculator.add_months(base_date, amount * 12)
                    elif unit == "工作日":
                        result = self.calculator.add_business_days(base_date, amount)
                    else:
                        raise ValueError(f"不支持的时间单位: {unit}")
                    
                    self.calculation_completed.emit(result)
                except Exception as retry_error:
                    QMessageBox.critical(self, "计算错误", f"计算过程中出现错误:\n{str(retry_error)}")
            else:
                QMessageBox.critical(self, "计算错误", f"计算过程中出现错误:\n{error_msg}")
    
    def calculate_interval(self):
        """计算日期间隔"""
        try:
            start_date = self.base_date_edit.date().toPyDate()
            end_date = self.end_date_edit.date().toPyDate()
            
            result = self.calculator.calculate_interval(start_date, end_date)
            
            # 格式化间隔结果
            interval_result = {
                'type': 'interval',
                'start_date': result['start_date'],
                'end_date': result['end_date'],
                'total_days': result['total_days'],
                'workdays': result['workdays'],
                'weekends': result['weekends'],
                'formatted_interval': result['formatted_interval']
            }
            
            self.display_interval_result(interval_result)
            
            # 添加到历史记录
            if self.history_manager:
                input_data = {
                    'start_date': str(start_date),
                    'end_date': str(end_date),
                    'calc_type': '间隔计算'
                }
                self.history_manager.add_calculation_record("日期间隔计算", input_data, interval_result)
            
        except Exception as e:
            QMessageBox.critical(self, "间隔计算错误", f"间隔计算过程中出现错误:\n{str(e)}")
    
    def display_result(self, result):
        """显示计算结果"""
        try:
            # 获取节假日名称
            holiday_name = ""
            if result['is_holiday']:
                holiday_name = self.calculator._get_holiday_name(result['result_date'])
                holiday_info = f"是（{holiday_name}）" if holiday_name else "是"
            else:
                holiday_info = "否"
            
            # 获取农历信息
            lunar_info = result.get('lunar_info', {})
            if lunar_info.get('has_lunar', False):
                lunar_text = f"\n🌙 农历信息:\n• 农历日期: {lunar_info['lunar_date']}\n• 生肖属相: {lunar_info['zodiac']}\n• 天干地支: {lunar_info['ganzhi']}"
            else:
                lunar_text = f"\n🌙 农历信息: {lunar_info.get('lunar_date', '转换失败')}"
            
            result_text = f"""
═══════════════════════════════════════
📅 日期计算结果
═══════════════════════════════════════

🗓️  基础日期: {result['base_date'].format('YYYY年MM月DD日 dddd')}
🎯  结果日期: {result['result_date'].format('YYYY年MM月DD日 dddd')}

📊 详细信息:
• 日期格式: {result['formatted_date']}
• 星期几: {result['weekday']}
• 是否周末: {'是' if result['is_weekend'] else '否'}
• 是否节假日: {holiday_info}
• 距今天数: {result['days_from_today']}天{lunar_text}

💡 提示: 结果日期为 {result['result_date'].format('YYYY年MM月DD日')}
{f'🎊 节日信息: {holiday_name}' if holiday_name else ''}
            """
            
            self.result_text.setPlainText(result_text.strip())
            
        except Exception as e:
            self.result_text.setPlainText(f"显示结果时出现错误: {str(e)}")
    
    def display_interval_result(self, result):
        """显示间隔计算结果"""
        try:
            result_text = f"""
═══════════════════════════════════════
📏 日期间隔计算结果
═══════════════════════════════════════

📅 开始日期: {result['start_date'].format('YYYY年MM月DD日 dddd')}
📅 结束日期: {result['end_date'].format('YYYY年MM月DD日 dddd')}

📊 间隔统计:
• 总天数: {result['total_days']}天
• 工作日: {result['workdays']}天
• 周末及节假日: {result['weekends']}天
• 格式化显示: {result['formatted_interval']}

💡 提示: 两个日期相差 {result['total_days']} 天
📝 注意: 工作日计算已考虑法定节假日和调休安排
            """
            
            self.result_text.setPlainText(result_text.strip())
            
        except Exception as e:
            self.result_text.setPlainText(f"显示间隔结果时出现错误: {str(e)}")
    
    def clear_inputs(self):
        """清空输入"""
        self.base_date_edit.setDate(QDate.currentDate())
        self.end_date_edit.setDate(QDate.currentDate().addDays(7))
        self.amount_spin.setValue(1)
        self.unit_combo.setCurrentIndex(0)
        self.add_radio.setChecked(True)
        self.result_text.clear()
    
    def copy_result(self):
        """复制结果到剪贴板"""
        result_text = self.result_text.toPlainText()
        if result_text:
            clipboard = QApplication.clipboard()
            clipboard.setText(result_text)
            
            # 创建一个浮动的成功提示
            self.show_floating_tip("✅ 复制成功！", "#28a745")
            
        else:
            # 没有结果时弹窗提醒
            QMessageBox.warning(self, "提示", "⚠️ 没有可复制的结果\n\n请先进行计算后再复制结果。")
    
    def show_floating_tip(self, message, color):
        """显示浮动提示"""
        from PyQt5.QtCore import QTimer
        from PyQt5.QtWidgets import QFrame
        
        # 创建卡片式提示框
        tip_frame = QFrame(self)
        tip_frame.setFrameStyle(QFrame.NoFrame)
        
        # 使用淡绿色背景
        tip_frame.setStyleSheet("""
            QFrame {
                background-color: rgba(212, 237, 218, 0.95);
                border: 1px solid rgba(40, 167, 69, 0.3);
                border-radius: 12px;
            }
        """)
        
        # 创建布局
        layout = QHBoxLayout(tip_frame)
        layout.setContentsMargins(16, 12, 16, 12)
        layout.setSpacing(12)
        
        # 创建圆形图标
        icon_label = QLabel("✓", tip_frame)
        icon_label.setStyleSheet("""
            QLabel {
                background-color: #28a745;
                color: white;
                border-radius: 15px;
                font-size: 14px;
                font-weight: bold;
                min-width: 30px;
                max-width: 30px;
                min-height: 30px;
                max-height: 30px;
            }
        """)
        icon_label.setAlignment(Qt.AlignCenter)
        
        # 创建文字标签
        text_label = QLabel("提交成功", tip_frame)
        text_label.setStyleSheet("""
            QLabel {
                color: #155724;
                font-size: 14px;
                font-weight: bold;
                background: transparent;
                border: none;
            }
        """)
        
        layout.addWidget(icon_label)
        layout.addWidget(text_label)
        
        # 调整框架大小
        tip_frame.adjustSize()
        tip_frame.setFixedSize(tip_frame.sizeHint())
        
        # 定位在应用的上半部分中央
        parent_rect = self.rect()
        tip_x = (parent_rect.width() - tip_frame.width()) // 2
        tip_y = parent_rect.height() // 5  # 放在上1/5位置
        tip_frame.move(tip_x, tip_y)
        
        # 显示提示框
        tip_frame.show()
        tip_frame.raise_()  # 确保在最顶层
        
        # 2秒后自动消失
        QTimer.singleShot(2000, tip_frame.deleteLater)
    
    def clear_all(self):
        """清空所有内容"""
        self.clear_inputs()
